#!/bin/sh
# udhcpc script edited by Tim Riker <Tim@Rikers.org>

. /usr/share/common

if [ -z "$1" ]; then
	echo_error "Error: should be called from udhcpc"
	exit 0
fi

if [ ! -d /sys/class/net/$interface ]; then
	echo_error "Interface $interface not found"
	exit 0
fi

NETMASK=""
[ -n "$subnet" ] && NETMASK="/$subnet"

BROADCAST="broadcast +"
[ -n "$broadcast" ] && BROADCAST="broadcast $broadcast"

# Define default metrics for interface types
DEFAULT_METRIC=100
WIRELESS_METRIC=200
WIRED_METRIC=100

# Function to determine the interface type
get_interface_type() {
	case "$1" in
		wlan* | wlp* | wls*)
			echo "wireless" ;;
		eth* | enp* | ens* | usb* | enx*)
			echo "wired" ;;
		*)
			echo "unknown" ;;
	esac
}

case "$1" in
	deconfig)
		ip -4 addr flush dev $interface up
		ip link set dev $interface up
		;;

	renew | bound)
		echo "Setting IP address $ip on $interface"
		ip addr add $ip$NETMASK $BROADCAST dev $interface
		if [ -n "$router" ]; then
			echo_info "Deleting routers"
			while route del default gw 0.0.0.0 dev $interface; do
				:
			done

			for i in $router; do
				echo_info "Adding router $i"
				if [ "$subnet" = "255.255.255.255" ]; then
					ip route add $i dev $interface
				fi
				# Set different metrics based on interface type
				IF_TYPE=$(get_interface_type $interface)
				case "$IF_TYPE" in
					wireless)
						route add default gw $i dev $interface metric $WIRELESS_METRIC
						;;
					wired)
						route add default gw $i dev $interface metric $WIRED_METRIC
						;;
					*)
						route add default gw $i dev $interface metric $DEFAULT_METRIC
						;;
				esac
			done
		fi
		;;
esac

for hook in "$0.d/"*; do
	[ -f "$hook" ] && [ -x "$hook" ] && $hook $1
done

exit 0
